<template>
    <div class="recruits-page">
        <!-- 顶部横幅 -->
        <PageHeader 
            title="加入我们" 
            subtitle="与易凡科技一起创造未来"
            :breadcrumbItems="[{ text: '首页', path: '/' }]"
            currentText="人才招聘"
        />

        <!-- 公司文化介绍 -->
        <section class="company-culture">
            <div class="page-container">
                <div class="culture-content">
                    <div class="culture-image">
                        <img :src="require('@/assets/images/about/办公环境5.jpg')" alt="公司文化">
                    </div>
                    <div class="culture-text">
                        <h2>公司文化</h2>
                        <p>在易凡科技，我们坚信人才是公司最宝贵的财富。我们致力于创造开放、包容、创新的工作环境，鼓励员工不断挑战自我，实现个人价值。</p>
                        <div class="culture-values">
                            <div class="value-item">
                                <i class="el-icon-star-on"></i>
                                <h3>创新</h3>
                                <p>拥抱变化，勇于创新，推动科技进步</p>
                            </div>
                            <div class="value-item">
                                <i class="el-icon-s-cooperation"></i>
                                <h3>协作</h3>
                                <p>团队合作，共同成长，实现共赢</p>
                            </div>
                            <div class="value-item">
                                <i class="el-icon-s-flag"></i>
                                <h3>卓越</h3>
                                <p>追求卓越，精益求精，超越自我</p>
                            </div>
                            <div class="value-item">
                                <i class="el-icon-s-claim"></i>
                                <h3>诚信</h3>
                                <p>诚实守信，言行一致，负责任</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 职位导航 -->
        <section class="job-navigation">
            <div class="page-container">
                <div class="section-header text-center">
                    <h2 class="section-title">职位类别</h2>
                    <p class="section-desc">探索适合您的职业发展道路</p>
                </div>
                <div class="job-categories">
                    <ul>
                        <li v-for="type in recruitTypes" :key="type.id">
                            <a href="#" 
                              :class="{ active: selectedType === type.id }" 
                              @click.prevent="selectType(type.id)">
                              {{ type.name }}
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </section>

        <!-- 职位列表 -->
        <section class="job-listings">
            <div class="page-container">
                <div class="job-category" v-if="loading">
                    <div class="loading-container text-center">
                        <el-icon class="is-loading"><Loading /></el-icon>
                        <p>加载职位数据中...</p>
                    </div>
                </div>
                
                <div v-else-if="recruitList.length === 0 && !loading" class="no-data text-center">
                    <i class="el-icon-warning-outline"></i>
                    <p>暂无相关职位信息</p>
                </div>
                
                <div v-else class="job-category">
                    <div class="category-header">
                        <h2>{{ getTypeName(selectedType) }}</h2>
                        <p>我们寻找优秀人才，共同打造行业领先的产品</p>
                    </div>
                    
                    <div class="job-list">
                        <div class="job-card" v-for="job in recruitList" :key="job._id">
                            <div class="job-header">
                                <h3 class="job-title">{{ job.position }}</h3>
                                <span class="job-location">{{ job.city }}</span>
                            </div>
                            <div class="job-body">
                                <div class="job-requirements">
                                    <h4>任职要求</h4>
                                    <div v-html="formatRequirement(job.requirement)"></div>
                                </div>
                            </div>
                            <div class="job-footer">
                                <span class="job-salary">薪资范围：{{ job.salary }}</span>
                                <el-button type="primary" @click="applyJob(job)">立即申请</el-button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 分页 -->
                <div class="pagination-container text-center" v-if="recruitList.length > 0">
                    <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="total"
                        :page-size="pageSize"
                        :current-page="currentPage"
                        @current-change="handlePageChange"
                    >
                    </el-pagination>
                </div>
            </div>
        </section>

        <!-- 福利待遇 -->
        <section class="job-benefits">
            <div class="page-container">
                <div class="section-header text-center">
                    <h2 class="section-title">加入我们的理由</h2>
                    <p class="section-desc">我们提供具有竞争力的薪酬和完善的福利体系</p>
                </div>
                
                <div class="benefits-container">
                    <div class="benefit-item">
                        <i class="el-icon-medal"></i>
                        <h3>具竞争力薪酬</h3>
                        <p>提供行业内具有竞争力的薪资水平和绩效奖金</p>
                    </div>
                    <div class="benefit-item">
                        <i class="el-icon-first-aid-kit"></i>
                        <h3>五险一金</h3>
                        <p>为员工提供完善的社会保险和住房公积金</p>
                    </div>
                    <div class="benefit-item">
                        <i class="el-icon-sunrise"></i>
                        <h3>带薪年假</h3>
                        <p>除法定节假日外，享受额外带薪年假和弹性工作时间</p>
                    </div>
                    <div class="benefit-item">
                        <i class="el-icon-reading"></i>
                        <h3>培训发展</h3>
                        <p>提供专业技能培训和职业发展规划</p>
                    </div>
                    <div class="benefit-item">
                        <i class="el-icon-dessert"></i>
                        <h3>团队活动</h3>
                        <p>定期组织团建活动和公司旅行</p>
                    </div>
                    <div class="benefit-item">
                        <i class="el-icon-trophy"></i>
                        <h3>晋升机会</h3>
                        <p>透明的晋升机制和广阔的职业发展空间</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- 申请流程 -->
        <section class="application-process">
            <div class="page-container">
                <div class="section-header text-center">
                    <h2 class="section-title">申请流程</h2>
                    <p class="section-desc">了解我们的招聘流程，做好充分准备</p>
                </div>
                
                <div class="process-steps">
                    <div class="process-step">
                        <div class="step-number">1</div>
                        <div class="step-info">
                            <h3>简历投递</h3>
                            <p>通过官网或招聘平台投递您的简历</p>
                        </div>
                    </div>
                    <div class="process-step">
                        <div class="step-number">2</div>
                        <div class="step-info">
                            <h3>简历筛选</h3>
                            <p>HR团队初步筛选符合要求的简历</p>
                        </div>
                    </div>
                    <div class="process-step">
                        <div class="step-number">3</div>
                        <div class="step-info">
                            <h3>技术面试</h3>
                            <p>与技术团队进行专业能力面试</p>
                        </div>
                    </div>
                    <div class="process-step">
                        <div class="step-number">4</div>
                        <div class="step-info">
                            <h3>综合面试</h3>
                            <p>与部门负责人进行深入交流</p>
                        </div>
                    </div>
                    <div class="process-step">
                        <div class="step-number">5</div>
                        <div class="step-info">
                            <h3>offer发放</h3>
                            <p>发放录用通知，确认入职事宜</p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 联系方式 -->
        <section class="contact-section">
            <div class="page-container">
                <div class="contact-info">
                    <h2>联系我们</h2>
                    <p>如有任何招聘相关问题，请随时与我们联系</p>
                    <div class="contact-methods">
                        <div class="contact-method">
                            <i class="el-icon-message"></i>
                            <span>招聘邮箱：hr@yifantech.com</span>
                        </div>
                        <div class="contact-method">
                            <i class="el-icon-phone"></i>
                            <span>招聘热线：0871-6543210</span>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 添加申请表单弹窗 -->
        <el-dialog
          v-model="dialogVisible"
          title="职位申请"
          width="500px"
        >
          <el-form 
            ref="applicationFormRef" 
            :model="applicationForm" 
            :rules="applicationRules" 
            label-width="80px"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="applicationForm.name" placeholder="请输入您的姓名" />
            </el-form-item>
            
            <el-form-item label="电话" prop="phone">
              <el-input v-model="applicationForm.phone" placeholder="请输入您的联系电话" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="applicationForm.email" placeholder="请输入您的邮箱地址" />
            </el-form-item>
            
            <el-form-item label="简历" prop="resume">
              <el-upload
                class="resume-upload"
                :auto-upload="false"
                :limit="1"
                :on-change="handleFileChange"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                accept=".pdf,.doc,.docx"
              >
                <el-button type="primary">选择简历文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">请上传PDF或Word格式的简历，文件大小不超过5MB</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitApplication" :loading="submitLoading">
                提交申请
              </el-button>
            </div>
          </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import PageHeader from '@/components/PageHeader.vue';
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import { recruitApi } from '@/api';

// 招聘数据管理
const recruitTypes = ref([]);
const recruitList = ref([]);
const selectedType = ref(1); // 默认选择技术岗位
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(6);

// 申请表单相关
const dialogVisible = ref(false);
const submitLoading = ref(false);
const currentJob = ref(null);
const applicationFormRef = ref(null);
const applicationForm = ref({
    name: '',
    phone: '',
    email: '',
    position: '',
    positionId: '',
    resume: null
});
const resumeFile = ref(null);

// 表单验证规则
const applicationRules = {
    name: [
        { required: true, message: '请输入您的姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2到20个字符之间', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入您的联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入您的邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    resume: [
        { required: true, message: '请上传您的简历', trigger: 'change' }
    ]
};


// 获取招聘类型
const getRecruitTypes = async () => {
    try {
        const res = await recruitApi.getRecruitTypes();
        if (res.data.ActionType === 'ok') {
            recruitTypes.value = res.data.data;
            // 如果获取类型成功，立即加载该类型下的招聘信息
            getRecruitList();
        }
    } catch (error) {
        console.error('获取招聘类型失败:', error);
        ElMessage.error('获取招聘类型失败，请刷新页面重试');
    }
};

// 获取招聘列表
const getRecruitList = async () => {
    loading.value = true;
    try {
        const res = await recruitApi.getRecruitList({
            page: currentPage.value,
            pageSize: pageSize.value,
            type: selectedType.value
        });
        
        if (res.data.ActionType === 'ok') {
            recruitList.value = res.data.data;
            total.value = res.data.total;
        }
    } catch (error) {
        console.error('获取招聘列表失败:', error);
        ElMessage.error('获取招聘信息失败，请稍后再试');
        recruitList.value = [];
    } finally {
        loading.value = false;
    }
};

// 选择职位类型
const selectType = (typeId) => {
    selectedType.value = typeId;
    currentPage.value = 1; // 切换类型时重置页码
    getRecruitList();
};

// 翻页处理
const handlePageChange = (page) => {
    currentPage.value = page;
    getRecruitList();
};

// 获取类型名称
const getTypeName = (typeId) => {
    const type = recruitTypes.value.find(t => t.id === typeId);
    return type ? type.name : '未知类型';
};

// 格式化职位要求，将字符串转为HTML
const formatRequirement = (requirement) => {
    if (!requirement) return '<p>暂无详细职位要求</p>';
    
    // 将纯文本转换为HTML列表格式
    const lines = requirement.split('\n').map(line => line.trim()).filter(line => line);
    
    if (lines.length === 0) return '<p>暂无详细职位要求</p>';
    
    return `<ul>${lines.map(line => `<li>${line}</li>`).join('')}</ul>`;
};

// 申请职位的处理函数
const applyJob = (job) => {
    currentJob.value = job;
    
    // 设置表单初始值
    applicationForm.value = {
        name: '',
        phone: '',
        email: '',
        position: job.position,
        positionId: job._id,
        resume: null
    };
    
    // 清除之前选择的文件
    resumeFile.value = null;
    
    // 打开申请表单对话框
    dialogVisible.value = true;
};

// 文件上传相关处理函数
const handleFileChange = (file) => {
    // 文件类型验证
    const acceptedTypes = ['.pdf', '.doc', '.docx'];
    const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    
    if (!acceptedTypes.includes(fileExt)) {
        ElMessage.error('只能上传PDF或Word格式的简历');
        return false;
    }
    
    // 文件大小验证（限制5MB）
    const maxSize = 5 * 1024 * 1024;
    if (file.size > maxSize) {
        ElMessage.error('文件大小不能超过5MB');
        return false;
    }
    
    resumeFile.value = file.raw;
    applicationForm.value.resume = file.raw;
    return true;
};

const handleExceed = () => {
    ElMessage.warning('最多只能上传1个文件');
};

const handleRemove = () => {
    resumeFile.value = null;
    applicationForm.value.resume = null;
};

// 提交申请
const submitApplication = () => {
    applicationFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true;
            
            try {
                // 创建FormData对象
                const formData = new FormData();
                
                // 添加表单数据
                Object.keys(applicationForm.value).forEach(key => {
                    if (key !== 'resume') { // 跳过resume字段，因为我们会单独添加文件
                        formData.append(key, applicationForm.value[key]);
                    }
                });
                
                // 添加文件
                formData.append('resume', resumeFile.value);
                
                // 提交申请
                const res = await recruitApi.submitJobApplication(formData);
                
                if (res.data.ActionType === 'ok') {
                    ElMessage.success('申请提交成功，我们会尽快与您联系');
                    dialogVisible.value = false;
                } else {
                    ElMessage.error(res.data.message || '申请提交失败，请稍后再试');
                }
            } catch (error) {
                console.error('提交申请失败:', error);
                ElMessage.error('申请提交失败，请稍后再试');
            } finally {
                submitLoading.value = false;
            }
        }
    });
};

// 页面加载时获取数据
onMounted(() => {
    getRecruitTypes();
});
</script>

<style lang="scss" scoped>
.recruits-page {
    padding-bottom: 60px;
    
    .company-culture {
        padding: 80px 0;
        background-color: #fff;
        
        .culture-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 50px;
            align-items: center;
            
            @media (max-width: 992px) {
                grid-template-columns: 1fr;
            }
            
            .culture-image {
                height: 400px;
                border-radius: 10px;
                overflow: hidden;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
                
                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }
            
            .culture-text {
                h2 {
                    font-size: 32px;
                    font-weight: 700;
                    color: #333;
                    margin-bottom: 20px;
                }
                
                p {
                    font-size: 16px;
                    color: #666;
                    line-height: 1.7;
                    margin-bottom: 30px;
                }
                
                .culture-values {
                    display: grid;
                    grid-template-columns: repeat(2, 1fr);
                    gap: 20px;
                    
                    .value-item {
                        padding: 20px;
                        background-color: #f9f9f9;
                        border-radius: 8px;
                        transition: transform 0.3s ease;
                        
                        &:hover {
                            transform: translateY(-5px);
                            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
                        }
                        
                        i {
                            font-size: 30px;
                            color: #409EFF;
                            margin-bottom: 10px;
                        }
                        
                        h3 {
                            font-size: 18px;
                            font-weight: 600;
                            color: #333;
                            margin-bottom: 10px;
                        }
                        
                        p {
                            font-size: 14px;
                            color: #666;
                            margin-bottom: 0;
                        }
                    }
                }
            }
        }
    }
    
    .job-navigation {
        padding: 50px 0 30px;
        background-color: #f5f7fa;
        
        .job-categories {
            margin-top: 30px;
            
            ul {
                display: flex;
                justify-content: center;
                flex-wrap: wrap;
                gap: 20px;
                list-style: none;
                padding: 0;
                
                li {
                    a {
                        display: block;
                        padding: 10px 20px;
                        background-color: #fff;
                        color: #333;
                        text-decoration: none;
                        border-radius: 4px;
                        font-weight: 500;
                        transition: all 0.3s ease;
                        border: 1px solid #e4e7ed;
                        
                        &:hover {
                            color: #409EFF;
                            border-color: #409EFF;
                        }
                        
                        &.active {
                            background-color: #409EFF;
                            color: #fff;
                            border-color: #409EFF;
                        }
                    }
                }
            }
        }
    }
    
    .job-listings {
        padding: 50px 0;
        
        .job-category {
            margin-bottom: 60px;
            
            .category-header {
                margin-bottom: 30px;
                border-left: 4px solid #409EFF;
                padding-left: 15px;
                
                h2 {
                    font-size: 24px;
                    font-weight: 600;
                    color: #333;
                    margin-bottom: 10px;
                }
                
                p {
                    color: #666;
                    font-size: 14px;
                }
            }
            
            .job-list {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 30px;
                
                @media (max-width: 992px) {
                    grid-template-columns: 1fr;
                }
                
                .job-card {
                    background-color: #fff;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
                    overflow: hidden;
                    transition: transform 0.3s ease;
                    
                    &:hover {
                        transform: translateY(-5px);
                        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
                    }
                    
                    .job-header {
                        padding: 20px;
                        border-bottom: 1px solid #f1f1f1;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        
                        .job-title {
                            font-size: 18px;
                            font-weight: 600;
                            color: #333;
                            margin: 0;
                        }
                        
                        .job-location {
                            background-color: #ecf5ff;
                            color: #409EFF;
                            padding: 5px 10px;
                            border-radius: 4px;
                            font-size: 12px;
                        }
                    }
                    
                    .job-body {
                        padding: 20px;
                        
                        .job-requirements, .job-responsibilities {
                            margin-bottom: 20px;
                            
                            h4 {
                                font-size: 16px;
                                font-weight: 600;
                                color: #333;
                                margin-bottom: 10px;
                            }
                            
                            ul {
                                padding-left: 20px;
                                color: #666;
                                font-size: 14px;
                                line-height: 1.7;
                                margin-bottom: 0;
                                
                                li {
                                    margin-bottom: 5px;
                                }
                            }
                        }
                    }
                    
                    .job-footer {
                        padding: 15px 20px;
                        background-color: #f9f9f9;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        
                        .job-salary {
                            color: #ff6b6b;
                            font-weight: 500;
                        }
                    }
                }
            }
        }
    }
    
    .job-benefits {
        padding: 80px 0;
        background-color: #f5f7fa;
        
        .benefits-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 30px;
            margin-top: 50px;
            
            @media (max-width: 992px) {
                grid-template-columns: repeat(2, 1fr);
            }
            
            @media (max-width: 576px) {
                grid-template-columns: 1fr;
            }
            
            .benefit-item {
                background-color: #fff;
                padding: 30px;
                border-radius: 8px;
                text-align: center;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
                transition: transform 0.3s ease;
                
                &:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
                }
                
                i {
                    font-size: 36px;
                    color: #409EFF;
                    margin-bottom: 15px;
                    display: block;
                }
                
                h3 {
                    font-size: 18px;
                    font-weight: 600;
                    color: #333;
                    margin-bottom: 10px;
                }
                
                p {
                    color: #666;
                    font-size: 14px;
                    line-height: 1.6;
                }
            }
        }
    }
    
    .application-process {
        padding: 80px 0;
        
        .process-steps {
            margin-top: 50px;
            display: flex;
            justify-content: space-between;
            position: relative;
            
            &:before {
                content: '';
                position: absolute;
                top: 40px;
                left: 70px;
                right: 70px;
                height: 3px;
                background-color: #e4e7ed;
                z-index: 0;
            }
            
            @media (max-width: 992px) {
                flex-direction: column;
                gap: 30px;
                
                &:before {
                    display: none;
                }
            }
            
            .process-step {
                display: flex;
                flex-direction: column;
                align-items: center;
                position: relative;
                z-index: 1;
                flex: 1;
                
                @media (max-width: 992px) {
                    flex-direction: row;
                    gap: 20px;
                }
                
                .step-number {
                    width: 80px;
                    height: 80px;
                    border-radius: 50%;
                    background-color: #409EFF;
                    color: #fff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 28px;
                    font-weight: 700;
                    margin-bottom: 20px;
                    box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
                }
                
                .step-info {
                    text-align: center;
                    
                    @media (max-width: 992px) {
                        text-align: left;
                    }
                    
                    h3 {
                        font-size: 18px;
                        font-weight: 600;
                        color: #333;
                        margin-bottom: 5px;
                    }
                    
                    p {
                        color: #666;
                        font-size: 14px;
                    }
                }
            }
        }
    }
    
    .contact-section {
        padding: 60px 0;
        background-color: #f5f7fa;
        
        .contact-info {
            max-width: 600px;
            margin: 0 auto;
            text-align: center;
            
            h2 {
                font-size: 28px;
                font-weight: 600;
                color: #333;
                margin-bottom: 15px;
            }
            
            p {
                color: #666;
                font-size: 16px;
                margin-bottom: 30px;
            }
            
            .contact-methods {
                display: flex;
                flex-direction: column;
                gap: 15px;
                
                .contact-method {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 10px;
                    
                    i {
                        font-size: 20px;
                        color: #409EFF;
                    }
                    
                    span {
                        font-size: 16px;
                        color: #333;
                    }
                }
            }
        }
    }
}

.section-header {
    margin-bottom: 30px;
    
    .section-title {
        font-size: 32px;
        font-weight: 700;
        color: #333;
        margin-bottom: 15px;
    }
    
    .section-desc {
        font-size: 16px;
        color: #666;
        max-width: 700px;
        margin: 0 auto;
    }
    
    &.text-center {
        text-align: center;
    }
}

.page-container {
    max-width: 1200px;
    padding: 0 15px;
    margin: 0 auto;
}

.loading-container {
    padding: 40px 0;
    
    .el-icon {
        font-size: 36px;
        color: #409EFF;
    }
    
    p {
        margin-top: 20px;
        color: #666;
    }
}

.no-data {
    padding: 60px 0;
    
    i {
        font-size: 48px;
        color: #ccc;
        margin-bottom: 15px;
    }
    
    p {
        color: #888;
        font-size: 16px;
    }
}

.pagination-container {
    margin-top: 40px;
}

.text-center {
    text-align: center;
}

.resume-upload {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-upload-list) {
  margin-top: 10px;
}
</style>